'use strict';
/**
 * Created by FreezeSoul on 2015/9/25.
 */
define([
        'angular',
        'app/layout/data-proxy-factory',
        'app/layout/layout-manager',
        'app/modules/include/define',
        'css!libs/golden-layout/src/css/goldenlayout-light-theme.css'
    ],
    function (angular, ProxyFactory, LayoutManager) {
        angular.module('ad.include')
            .directive('adIncludeDashboardDirective', ['$rootScope', '$state', 'adIncludeService', function ($rootScope, $state, service) {
                return {
                    templateUrl: 'app/modules/include/views/dashboard.tpl.html',
                    restrict: 'E',
                    replace: true,
                    scope: {
                        pageid: '=',
                        startload: '='
                    },
                    link: function ($scope, $elm, $attrs, $ctrl) {

                        $scope.$watch('startload', function (newValue, oldValue) {
                            if (newValue === true) {
                                if ($scope.pageid) {
                                    if ($scope.$parent.layoutPlugin)
                                        $scope.$parent.layoutPlugin.dispose();
                                    var proxy = new ProxyFactory(service.loadDataSet).create();
                                    var layout = new LayoutManager($elm[0], $scope, proxy, service.loadChart, service.loadUserPage);
                                    layout.init($scope.pageid, [], false);
                                    $scope.$parent.layoutPlugin = layout;
                                    layout._globleEmitter.addListener("navigate", function (params) {
                                        $state.go('include', {pageid: params.pageId}, {
                                            notify: false
                                        })
                                    });
                                }
                            }
                        }, true);

                        var setTimeResizeHandle = undefined;

                        var resize = function () {
                            if ($scope.$parent.layoutPlugin) {
                                $scope.$parent.layoutPlugin.resize();
                            }
                        };
                        var setTimeResize = function () {
                            clearTimeout(setTimeResizeHandle);
                            setTimeResizeHandle = setTimeout(resize, 500);
                        };
                        $(window).off("resize", setTimeResize);
                        $(window).on("resize", setTimeResize);
                    }
                }
            }]);

    });
